<?php
namespace app\common\service;

use app\common\helper\CoursePosterHelper;
use think\Model;

class PosterService extends BaseService
{

    /**
     * 后台: 获取海报列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getAdminPosterList($sid, $p, $pageSize){
        $field = 'poster_id,poster_name,poster_imgs,add_time,edit_time';
        $list = db('poster')
            ->field($field)
            ->where(['sid' => $sid, 'status' => 1])
            ->limit(($p-1)*$pageSize, $pageSize)
            ->order('add_time DESC')
            ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['poster_imgs'] = json_decode($v['poster_imgs'], 1);
                $list[$k]['edit_time'] = $v['edit_time'] ? date('Y-m-d H:i:s', $v['edit_time']) : date('Y-m-d H:i:s', $v['add_time']);
            }
        }

        $count = db('poster')->where(['sid' => $sid, 'status' => 1])->count();
        $data = [
            'page' => ['count' => $count],
            'content' => $list
        ];
        return $data;
    }

    /**
     * 后台: 新增或编辑海报
     * @param $sid
     * @param $poster_id
     * @param $poster_name
     * @param $poster_imgs
     * @return array
     * @throws \think\Exception
     */
    public function savePoster($sid, $poster_id, $poster_name, $poster_imgs){
        foreach($poster_imgs as $k => $v){
            //获取图片宽高，并计算图片比例(9:16)是否合法
            $img_size = getimagesize($v);
            list($w, $h) = $img_size;
            if($w*16 != $h*9){
                return ['status' => 0, 'msg' => '第'.($k+1).'张上传图片尺寸比例不正确，请重新选择宽高比例为9:16的图片'];
            }
        }

        $data = [
            'poster_name' => $poster_name,
            'poster_imgs' => json_encode($poster_imgs)
        ];

        if($poster_id > 0){
            $data['edit_time'] = time();
            $r = db('poster')->where(['poster_id' => $poster_id, 'status' => 1])->update($data);
        } else {
            $data['sid'] = $sid;
            $data['add_time'] = time();
            $r = db('poster')->insert($data);
        }

        return $r ? ['status' => 1, 'msg' => '上传成功'] : ['status' => 0, 'msg' => '上传失败'];
    }

    /**
     * 后台: 删除海报
     * @param $sid
     * @param $poster_id
     * @return int
     */
    public function deletePoster($sid, $poster_id){
        return db('poster')->where(['poster_id' => $poster_id, 'sid' => $sid])->setField('status', -1);
    }

    /**
     * 微信端: 获取海报列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getFrontPosterList($sid, $p, $pageSize){
        $field = 'poster_id,poster_name';
        $list = db('poster')
                ->field($field)
                ->where(['sid' => $sid, 'status' => 1])
                ->limit(($p-1)*$pageSize, $pageSize)
                ->order('add_time DESC')
                ->select();
        return $list;
    }

    public function getPosterImgs($sid, $uid, $poster_id){
        $poster = db('poster')->where(['sid' => $sid, 'poster_id' => $poster_id, 'status' => 1])->find();
        if(empty($poster)){
            return ['status' => 0, 'msg' => '海报不存在'];
        }

        if(empty($poster['poster_imgs'])){
            return ['status' => 0, 'msg' => '当前海报为空'];
        }

        $poster_imgs = json_decode($poster['poster_imgs'], 1);
//        $poster_imgs[0] = 'http://or5rqhyqy.bkt.clouddn.com/0a6a6c8780dcd1c7b8fb2d87995f699f4dd6ee591511228571';

        //获取顾问ID
        $counselor_id = $this->getCounselorIdByUid($sid, $uid);
        if(!$counselor_id){
            return ['status' => 0, 'msg' => '生成海报失败'];
        }

        //获取二维码URL地址
        $wxService = new WeixinService();
        $qrcode = $wxService->get_user_qrcode($sid, $counselor_id);
        $qrcode_arr = json_decode($qrcode['data'], 1);
        $qrcode_url = $qrcode_arr['qrcode_url'];

        //创建海报
        $data = $this->buildPoster($uid, $poster_imgs, $qrcode_url);

        return ['status' => 1, 'data' => $data, 'msg' => '获取成功'];
    }


    /**
     * 获取顾问ID
     * @param $uid
     * @return mixed
     */
    public function getCounselorIdByUid($sid, $uid){
        $user = db('user_integral')->field('counselor_status,counselor_id')->where(['userid' => $uid])->find();
        if($user['counselor_status'] == 1){
            return $uid;
        } else {
            if($user['counselor_id']){
                $counselor_id = db('user_integral')->where(['userid' => $user['counselor_id']])->value('userid');
            } else {
                $counselor_id = db('user_integral')->where(['is_administrator' => 1, 'sid' => $sid])->value('userid');
            }
            return $counselor_id;
        }
    }


    /**
     * 创建海报
     * @param $uid
     * @param array $posters
     * @param $qrcode_url
     * @return array|bool
     */
    public function buildPoster($uid, $posters = [], $qrcode_url){
        foreach($posters as $k => $v){
            list($poster_w, $poster_h) = getimagesize($v);
            //图片比例9:16
            if($poster_w * 16 != $poster_h * 9){
                unset($posters[$k]);
            }
        }
        if(!$posters){
            return false;
        }

        $data = $this->createPoster($uid, $qrcode_url, $posters);
        foreach($data as $k => $v){
            $data[$k] = $this->domain.$v;
        }
        return $data;
    }

    /**
     * 将二维码等比例缩放
     * @param $save_path
     * @param $qrcode_url
     * @return string
     */
    public function qrcodeScale($save_path, $qrcode_url){
        $img_path = $save_path . DS . 'qrcode.jpg';
        if(file_exists($img_path)){
            return $img_path;
        }

        $qrcode_org = imagecreatefromjpeg($qrcode_url);
        list($src_w, $src_y) = getimagesize($qrcode_url);
        $dst_w = 164;
        $dst_y = 164;

        $qrcode_new = imagecreatetruecolor(164, 164);

        imagecopyresized($qrcode_new, $qrcode_org, 0, 0, 0, 0, $dst_w, $dst_y, $src_w, $src_y);
        imagejpeg($qrcode_new, $img_path);
        imagedestroy($qrcode_org);
        imagedestroy($qrcode_new);
        return $img_path;
    }

    /**
     * 将二维码和背景图片合成海报
     * @param $uid
     * @param $qrcode_url
     * @param $posters
     * @return array
     */
    public function createPoster($uid, $qrcode_url, $posters){
        $save_path = ROOT_PATH .'public'.DS.'uploads'.DS .'poster'.DS.$uid;
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }

        //生成二维码
//        $qr = Util::createQRcode($save_path, $qrcode);
        //调整二维码大小
        $qrcode_path = $this->qrcodeScale($save_path, $qrcode_url);
        $qrcode = imagecreatefromjpeg($qrcode_path);;

        $data = [];
        foreach($posters as $k => $v){
            $bg_info = pathinfo($v);
            $basename = $bg_info['basename'];

            //判断是否已经生成过
            $img_name = $basename.'_pr.jpg';
            $img_path = $save_path . DS . $img_name;
            $img_url = '/uploads'. DS . 'poster'. DS .$uid . DS . $img_name;
            if(file_exists($img_path)){
                $data[$k] = $img_url;
                continue;
            }

            //等比例缩放背景图
            $coursePosterHelper = new CoursePosterHelper();
            $r = $coursePosterHelper->bgScale($save_path, $v, $basename);

            $bg = imagecreatefromjpeg($r);

            $img = imageCreatetruecolor(imagesx($bg), imagesy($bg));

            $color = imagecolorallocate($img, 255, 255, 255);
            imagefill($img, 0, 0, $color);
            imageColorTransparent($img, $color);

            imagecopyresampled($img, $bg, 0, 0, 0, 0, imagesx($bg), imagesy($bg), imagesx($bg), imagesy($bg));

            imagecopymerge($img, $qrcode, 514, 1026, 0, 0, imagesx($qrcode), imagesy($qrcode), 100);

            imagejpeg($img, $img_path, 50);
            imagedestroy($img);

            $data[$k] = $img_url;
        }
        return $data;
    }
}







